import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../services/storage/local_storage_service.dart';
import '../services/theme_service.dart';

/// 主题控制器
/// 负责管理应用主题
class ThemeController extends GetxController {
  // 单例访问器
  static ThemeController get to => Get.find();
  
  // 注入服务
  final ThemeService _themeService = Get.find<ThemeService>();
  final LocalStorageService _storageService = Get.find<LocalStorageService>();
  
  // 当前主题模式
  final Rx<ThemeMode> _themeMode = ThemeMode.system.obs;
  ThemeMode get themeMode => _themeMode.value;
  
  // 是否为暗色主题
  bool get isDarkMode => _themeMode.value == ThemeMode.dark;
  
  // 主题存储键
  static const String themeKey = 'app_theme_mode';
  
  @override
  void onInit() {
    super.onInit();
    
    // 初始化主题
    _loadTheme();
  }
  
  /// 加载保存的主题
  void _loadTheme() {
    final String? savedTheme = _storageService.read(themeKey);
    
    if (savedTheme != null) {
      switch (savedTheme) {
        case 'light':
          _themeMode.value = ThemeMode.light;
          break;
        case 'dark':
          _themeMode.value = ThemeMode.dark;
          break;
        default:
          _themeMode.value = ThemeMode.system;
          break;
      }
    } else {
      // 默认使用系统主题
      _themeMode.value = ThemeMode.system;
    }
    
    // 更新主题服务
    _themeService.updateThemeMode(_themeMode.value);
  }
  
  /// 切换明暗主题
  void toggleTheme() {
    final ThemeMode newMode = isDarkMode ? ThemeMode.light : ThemeMode.dark;
    changeThemeMode(newMode);
  }
  
  /// 更改主题模式
  void changeThemeMode(ThemeMode mode) {
    _themeMode.value = mode;
    
    // 保存设置
    String themeSetting;
    switch (mode) {
      case ThemeMode.light:
        themeSetting = 'light';
        break;
      case ThemeMode.dark:
        themeSetting = 'dark';
        break;
      case ThemeMode.system:
      default:
        themeSetting = 'system';
        break;
    }
    
    _storageService.write(themeKey, themeSetting);
    
    // 更新主题服务
    _themeService.updateThemeMode(mode);
    
    // 更新GetX主题
    Get.changeThemeMode(mode);
  }
  
  /// 使用系统主题
  void useSystemTheme() {
    changeThemeMode(ThemeMode.system);
  }
  
  /// 使用亮色主题
  void useLightTheme() {
    changeThemeMode(ThemeMode.light);
  }
  
  /// 使用暗色主题
  void useDarkTheme() {
    changeThemeMode(ThemeMode.dark);
  }
} 